﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using NHTU;

namespace NOMFinalSettlement.AppForm.Program
{
    public partial class fSignFinally : DevComponents.DotNetBar.Office2007Form
    {
        FinalSettlementModel.TableNhomCongTrinh groupProject = null;
        FinalSettlementModel.TableQuyetDinhDauTu acceptInvestment = null;
        FinalSettlementModel.TableChuDauTu investor = null;
        FinalSettlementModel.TableHinhThucChonThau construct = null;
        FinalSettlementModel.TableCanBo examine = null;
        FinalSettlementModel.TableNguonVon capital = null;
        FinalSettlementModel.TableHoSo profileDB = null;
        FinalSettlementModel.TablePheDuyet approveProfile = null;
        FinalSettlementModel.TableNguonVon_PheDuyet capitalApprove = null;

        int idProfileSelected = -1;
        int idApproveSelected = -1;

        DataTable profileTable = null;
        DataTable approveTable = null;

        public fSignFinally()
        {
            InitializeComponent();
        }

        private void fSignFinally_Load(object sender, EventArgs e)
        {
            enableProfileControl(false);

            //Khoi tạo lớp model của TableNguonVon_PheDuyet
            capitalApprove = new FinalSettlementModel.TableNguonVon_PheDuyet();

            // Khởi tạo lớp model của TableNhomCongTrinh
            groupProject = new FinalSettlementModel.TableNhomCongTrinh();
            groupProject.EventLoadData += new FinalSettlementModel.TableNhomCongTrinh.LoadData(OnLoadGroupProject);
            doLoadDataComboboxGroupProject();

            // Khởi tạo lớp model của TableQuyetDinhDauTu
            acceptInvestment = new FinalSettlementModel.TableQuyetDinhDauTu();
            acceptInvestment.EventLoadData += new FinalSettlementModel.TableQuyetDinhDauTu.LoadData(OnLoadAcceptInvestment);
            doLoadDataComboboxAcceptInvestment();

            // Khởi tạo lớp model của TableChuDauTu
            investor = new FinalSettlementModel.TableChuDauTu();
            investor.EventLoadData += new FinalSettlementModel.TableChuDauTu.LoadData(OnLoadInvestor);
            doLoadDataComboboxInvestor();

            // Khởi tạo lớp model của TableHinhThucChonThau
            construct = new FinalSettlementModel.TableHinhThucChonThau();
            construct.EventLoadData += new FinalSettlementModel.TableHinhThucChonThau.LoadData(OnLoadConstructName);
            doLoadDataComboboxConstructName();

            // Khởi tạo lớp model của TableCanBo
            examine = new FinalSettlementModel.TableCanBo();
            examine.EventLoadData += new FinalSettlementModel.TableCanBo.LoadData(OnLoadExamineData);
            doloadDataListUser();

            // Khởi tạo lớp model của TableNguonVon
            capital = new FinalSettlementModel.TableNguonVon();
            capital.EventLoadData += new FinalSettlementModel.TableNguonVon.LoadData(OnLoadCapitalData);
            doloadCapitalInvestment();

            // Khởi tạo lớp model của TblHoSo
            profileDB = new FinalSettlementModel.TableHoSo();
            profileDB.EventLoadData += new FinalSettlementModel.TableHoSo.LoadData(OnLoadProfileData);
            doLoadUseProfile();

            // Khởi tạo lớp model của TblPheDuyet
            approveProfile = new FinalSettlementModel.TablePheDuyet();
            approveProfile.EventLoadData += new FinalSettlementModel.TablePheDuyet.LoadData(OnLoadApproveData);
            doLoadDataSignFinally();

        }

        void OnLoadGroupProject()
        {
            ISynchronizeInvoke i = (ISynchronizeInvoke)this;
            if (i.InvokeRequired)
            {
                FinalSettlementModel.TableNhomCongTrinh.LoadData tmpTableNhomCongTrinh = new FinalSettlementModel.TableNhomCongTrinh.LoadData(OnLoadGroupProject);
                i.BeginInvoke(tmpTableNhomCongTrinh, null);
                return;
            }
            doLoadDataComboboxGroupProject();
        }
        void OnLoadAcceptInvestment()
        {
            ISynchronizeInvoke i = (ISynchronizeInvoke)this;
            if (i.InvokeRequired)
            {
                FinalSettlementModel.TableQuyetDinhDauTu.LoadData tmpTableQuyetDinhDauTu = new FinalSettlementModel.TableQuyetDinhDauTu.LoadData(OnLoadAcceptInvestment);
                i.BeginInvoke(tmpTableQuyetDinhDauTu, null);
                return;
            }
            doLoadDataComboboxAcceptInvestment();
        }
        void OnLoadInvestor()
        {
            ISynchronizeInvoke i = (ISynchronizeInvoke)this;
            if (i.InvokeRequired)
            {
                FinalSettlementModel.TableChuDauTu.LoadData tmpTableChuDauTu = new FinalSettlementModel.TableChuDauTu.LoadData(OnLoadInvestor);
                i.BeginInvoke(tmpTableChuDauTu, null);
                return;
            }
            doLoadDataComboboxInvestor();
        }
        void OnLoadConstructName()
        {
            ISynchronizeInvoke i = (ISynchronizeInvoke)this;
            if (i.InvokeRequired)
            {
                FinalSettlementModel.TableHinhThucChonThau.LoadData tmpTableHinhThucChonThau = new FinalSettlementModel.TableHinhThucChonThau.LoadData(OnLoadConstructName);
                i.BeginInvoke(tmpTableHinhThucChonThau, null);
                return;
            }
            doLoadDataComboboxConstructName();
        }
        void OnLoadExamineData()
        {
            ISynchronizeInvoke i = (ISynchronizeInvoke)this;
            if (i.InvokeRequired)
            {
                FinalSettlementModel.TableCanBo.LoadData tmpDelegate = new FinalSettlementModel.TableCanBo.LoadData(OnLoadExamineData);
                i.BeginInvoke(tmpDelegate, null);
                return;
            }
            doloadDataListUser();
        }
        void OnLoadCapitalData()
        {
            ISynchronizeInvoke i = (ISynchronizeInvoke)this;
            if (i.InvokeRequired)
            {
                FinalSettlementModel.TableNguonVon.LoadData tmpDelegate = new FinalSettlementModel.TableNguonVon.LoadData(OnLoadCapitalData);
                i.BeginInvoke(tmpDelegate, null);
                return;
            }
            doloadCapitalInvestment();
        }
        void OnLoadProfileData()
        {
            ISynchronizeInvoke i = (ISynchronizeInvoke)this;
            if (i.InvokeRequired)
            {
                FinalSettlementModel.TableHoSo.LoadData tmpDelegate = new FinalSettlementModel.TableHoSo.LoadData(OnLoadProfileData);
                i.BeginInvoke(tmpDelegate, null);
                return;
            }
            doLoadUseProfile();
        }
        void OnLoadApproveData()
        {
            ISynchronizeInvoke i = (ISynchronizeInvoke)this;
            if (i.InvokeRequired)
            {
                FinalSettlementModel.TablePheDuyet.LoadData tmpDelegate = new FinalSettlementModel.TablePheDuyet.LoadData(OnLoadApproveData);
                i.BeginInvoke(tmpDelegate, null);
                return;
            }
            doLoadDataSignFinally();
        }

        #region Sự kiện
        private void btnEdit_Click(object sender, EventArgs e)
        {
            if (!superValidator1.Validate())
            {
                MsgBox.Show("Vui lòng nhập đầy đủ các thông tin yêu cầu.", "Thông báo", NHTU.MsgBoxButton.Ok, NHTU.MsgBoxIcon.Stop);
                return;
            }            
            doUpdateInfoProfile();
            reloadControl();    
        }

        private void btnSave_Click(object sender, EventArgs e)
        {
            if (!superValidator2.Validate())
            {
                MsgBox.Show("Vui lòng nhập đầy đủ các thông tin yêu cầu.", "Thông báo", NHTU.MsgBoxButton.Ok, NHTU.MsgBoxIcon.Stop);
                return;
            }
            doUpdate();
            reloadControl();
        }

        private void btnAddCapital_Click(object sender, EventArgs e)
        {
            foreach (DataGridViewRow r in dataGridCapitalInvestment.Rows)
            {
                if (r.Cells[1].Value.ToString() == cbbCapital.SelectedValue.ToString())
                {
                    MsgBox.Show("Dữ liệu này đã được nhập.", "Thông báo", NHTU.MsgBoxButton.Ok, NHTU.MsgBoxIcon.Stop);
                    return;
                }
            }
            dataGridCapitalInvestment.Rows.Add(0, cbbCapital.SelectedValue,
                                                cbbCapital.SelectedNode.Cells[0].Text,
                                                Convert.ToDouble(cbbCapital.SelectedNode.Cells[1].Text));
        }

        private void colDELETE_Click(object sender, EventArgs e)
        {
            foreach (DataGridViewRow item in this.dataGridCapitalInvestment.SelectedRows)
            {
                dataGridCapitalInvestment.Rows.RemoveAt(item.Index);
            }
        }

        private void dataGrid_CellMouseClick(object sender, DataGridViewCellMouseEventArgs e)
        {
            superValidator1.ClearFailedValidations();
            superValidator2.ClearFailedValidations();

            idApproveSelected = MainApp.Self.appProcess.getIdGrid(dataGrid, e, null);

            if (idApproveSelected < 1)
            {

                enableProfileControl(false);
                reloadControl();
            }
            else
            {
                enableProfileControl(true);

                //Lấy dữ liệu từ grid ra text box
                DataGridViewSelectedRowCollection selectRows = dataGrid.SelectedRows;
                foreach (DataGridViewRow row in selectRows)
                {
                    if (row.Cells[0].Value != null)
                    {
                        doSearchApproveDataTable(idApproveSelected);
                    }
                }
            }
        }
        #endregion

        #region Hàm xử lý
        void doSearchApproveDataTable(int approveId)
        {
            DataRow[] dr = approveTable.Select(String.Format("ID='{0}'", approveId.ToString()));
            if (dr.Count() > 0)
            {
                foreach (DataRow approveRow in dr)
                {
                    idProfileSelected = (int)approveRow["HoSoID"];

                    foreach (DataRow profileRow in profileTable.Select(String.Format("ID='{0}'", idProfileSelected.ToString())))
                    {
                        txtProjectName.Text = profileRow["TenDuAn"].ToString();
                        txtProjectCode.Text = profileRow["MaDuAn"].ToString();
                        cbbGroupProject.Text = profileRow["NhomCongTrinh"].ToString();
                        cbbAcceptInvestment.Text = profileRow["QuyetDinhDauTu"].ToString();
                        cbbInvestor.Text = profileRow["ChuDauTu"].ToString();
                        dateAddDoc.Text = profileRow["NgayNhan"].ToString();
                        totalProject.Text = profileRow["TongDuAn"].ToString();
                        totalEstimates.Text = profileRow["TongDuToan"].ToString();
                        totalSettlement.Text = profileRow["DeNghiQuyetToan"].ToString();
                        cbbConstructName.Text = profileRow["HinhThucChonThau"].ToString();
                        cbbExamineUser.Text = profileRow["CanBo"].ToString();
                    }
                    
                    txtLocation.Text = approveRow["DiaDiem"].ToString();
                    dateStart.Text = approveRow["TGKhoiCong"].ToString();
                    dateFinish.Text = approveRow["TGHoanThanh"].ToString();
                    txtScale.Text = approveRow["QuyMoDauTu"].ToString();
                    inputTotalSettlement.Text = approveRow["GTQTDuocDuyet"].ToString();
                    inputConstructionCosts.Text = approveRow["ChiPhiXayDung"].ToString();
                    inputEquipmentCosts.Text = approveRow["ChiPhiThietBi"].ToString();
                    inputManagerCosts.Text = approveRow["ChiPhiQLDA"].ToString();
                    inputConsultancyCosts.Text = approveRow["ChiPhiTVDT"].ToString();
                    inputClearanceCosts.Text = approveRow["ChiPhiBTGPMB"].ToString();
                    inputOtherCosts.Text = approveRow["ChiPhiKhac"].ToString();
                    txtCode.Text = approveRow["SoLuu"].ToString();
                    dateSignFinal.Text = approveRow["NgayPheDuyet"].ToString();
                    txtDocSignFinal.Text = approveRow["VanBanPheDuyet"].ToString();
                    txtSignFinalPrice.Text = approveRow["PhiThamTra"].ToString();
                    txtNote.Text = approveRow["GhiChu"].ToString();
                    if (approveRow["TrinhKy"].ToString() == "True")
                    {
                        chkApplySign.Checked = true;
                    }
                    else chkApplySign.Checked = false;

                    if (approveRow["HoanThanh"].ToString() == "True")
                    {
                        chkFinish.Checked = true;
                    }
                    else chkFinish.Checked = false;

                    var capApp = capitalApprove.ListCapital_ApproveData((int)approveRow["ID"]);
                    dataGridCapitalInvestment.Rows.Clear();
                    foreach (var cap in capApp)
                    {
                        dataGridCapitalInvestment.Rows.Add(cap.ID, cap.NguonVonId, cap.TblNguonVon.NguonVon, (double)cap.TblNguonVon.GiaTri);
                    }
                }
            }
            else
            {
                reloadControl();
            }
        }

        void doLoadDataSignFinally()
        {
            dataGrid.Rows.Clear();
            approveTable = approveProfile.ListSignApproveData();

            foreach (DataRow row in approveTable.Rows)
            {
                if (dataGrid.ColumnCount > 0)
                {
                    dataGrid.Rows.Add(row["ID"], row["TenDuAn"]);
                }
            }
            profileTable = profileDB.ListUseProfileData();
        }
        void doLoadUseProfile()
        {
            profileTable = profileDB.ListUseProfileData();
        }
        //Data to Commbobox
        void doLoadDataComboboxGroupProject()
        {
            cbbGroupProject.DataSource = groupProject.ListGroupObjectData();
            cbbGroupProject.DisplayMember = "NhomCongTrinh";
            cbbGroupProject.ValueMember = "ID";
        }
        void doLoadDataComboboxAcceptInvestment()
        {
            cbbAcceptInvestment.DataSource = acceptInvestment.ListInvestmentData();
            cbbAcceptInvestment.DisplayMember = "QuyetDinhDauTu";
            cbbAcceptInvestment.ValueMember = "ID";
        }
        void doLoadDataComboboxInvestor()
        {
            cbbInvestor.DataSource = investor.ListInvestorData();
            cbbInvestor.DisplayMember = "ChuDauTu";
            cbbInvestor.ValueMember = "ID";
        }
        void doLoadDataComboboxConstructName()
        {
            cbbConstructName.DataSource = construct.ListBidData();
            cbbConstructName.DisplayMember = "HinhThucChonThau";
            cbbConstructName.ValueMember = "ID";
        }
        void doloadDataListUser()
        {
            cbbExamineUser.DataSource = examine.ListOfficerData();
            cbbExamineUser.DisplayMember = "CanBo";
            cbbExamineUser.ValueMember = "ID";
        }
        void doloadCapitalInvestment()
        {
            cbbCapital.DataSource = capital.ListCapitalData();
            cbbCapital.DisplayMembers = "NguonVon,GiaTri";
            cbbCapital.ValueMember = "ID";
        }

        void doUpdateInfoProfile()
        {
            if (profileDB.checkProfileName(idProfileSelected, txtProjectName.Text))
            {
                profileDB.updateProfile(idProfileSelected,
                                        txtProjectName.Text,
                                        txtProjectCode.Value,
                                        (int)cbbGroupProject.SelectedValue,
                                        (int)cbbAcceptInvestment.SelectedValue,
                                        (int)cbbInvestor.SelectedValue,
                                        dateAddDoc.Value,
                                        (decimal)totalProject.Value,
                                        (decimal)totalEstimates.Value,
                                        (decimal)totalSettlement.Value,
                                        (int)cbbConstructName.SelectedValue,
                                        MainApp.Self.DBUSER.ID);
                profileDB.updateExamine(idProfileSelected, (int)cbbExamineUser.SelectedValue);
            }
            else
            {
                MsgBox.Show("Dữ liệu này đã tồn tại. Vui lòng kiểm tra lại!", "Thông Báo", MsgBoxButton.YesNo, MsgBoxIcon.Question);
            }
        }

        void doUpdate()
        {
            if (approveProfile.checkApproveName(idApproveSelected, idProfileSelected))
            {
                approveProfile.updateApprove(idApproveSelected,
                                            idProfileSelected,
                                            txtLocation.Text,
                                            dateStart.Value,
                                            dateFinish.Value,
                                            txtScale.Text,
                                            (decimal)inputTotalSettlement.Value,
                                            (decimal)inputConstructionCosts.Value,
                                            (decimal)inputEquipmentCosts.Value,
                                            (decimal)inputManagerCosts.Value,
                                            (decimal)inputConsultancyCosts.Value,
                                            (decimal)inputClearanceCosts.Value,
                                            (decimal)inputOtherCosts.Value,
                                            chkApplySign.Checked,
                                            txtCode.Text,
                                            dateSignFinal.Value,
                                            txtDocSignFinal.Text,
                                            (decimal)txtSignFinalPrice.Value,
                                            chkFinish.Checked,
                                            txtNote.Text);
                capitalApprove.deleteCapital_Approve(idApproveSelected);
                if (dataGridCapitalInvestment.Rows.Count > 0)
                {
                    foreach (DataGridViewRow row in dataGridCapitalInvestment.Rows)
                    {
                        capitalApprove.insertCapital_Approve(idApproveSelected, (int)row.Cells[1].Value);
                    }
                }
            }
            else
            {
                MsgBox.Show("Dữ liệu này đã tồn tại. Vui lòng kiểm tra lại!", "Thông Báo", MsgBoxButton.YesNo, MsgBoxIcon.Question);
            }
        }
        #endregion

        #region Hàm dùng chung
        void enableProfileControl(bool yes)
        {
            btnEdit.Enabled = yes;
            btnSave.Enabled = yes;
            dataGridCapitalInvestment.Enabled = yes;
            cbbCapital.Enabled = yes;
            btnAddCapital.Enabled = yes;

            txtProjectName.Enabled = yes;
            txtProjectCode.Enabled = yes;
            cbbGroupProject.Enabled = yes;
            cbbAcceptInvestment.Enabled = yes;
            cbbInvestor.Enabled = yes;
            dateAddDoc.Enabled = yes;
            totalProject.Enabled = yes;
            totalEstimates.Enabled = yes;
            totalSettlement.Enabled = yes;
            cbbConstructName.Enabled = yes;
            cbbExamineUser.Enabled = yes;

            txtLocation.Enabled = yes;
            dateStart.Enabled = yes;
            dateFinish.Enabled = yes;
            txtScale.Enabled = yes;
            inputTotalSettlement.Enabled = yes;
            inputManagerCosts.Enabled = yes;
            inputOtherCosts.Enabled = yes;
            inputClearanceCosts.Enabled = yes;
            inputConstructionCosts.Enabled = yes;
            inputEquipmentCosts.Enabled = yes;
            inputConsultancyCosts.Enabled = yes;
            chkApplySign.Enabled = yes;

            txtCode.Enabled = yes;
            dateSignFinal.Enabled = yes;
            txtDocSignFinal.Enabled = yes;
            txtSignFinalPrice.Enabled = yes;
            txtNote.Enabled = yes;
            chkFinish.Enabled = yes;
        }
        void reloadControl()
        {
            idProfileSelected = -1;
            idApproveSelected = -1;

            txtProjectName.Text = "";
            txtProjectCode.Text = null;
            cbbGroupProject.Text = "";
            cbbAcceptInvestment.Text = "";
            cbbInvestor.Text = "";
            dateAddDoc.Text = "";
            totalProject.Text = null;
            totalEstimates.Text = null;
            totalSettlement.Text = null;
            cbbConstructName.Text = "";
            cbbExamineUser.Text = "";

            txtLocation.Text = "";
            dateStart.Text = "";
            dateFinish.Text = "";
            txtScale.Text = "";
            inputTotalSettlement.Text = null;
            inputManagerCosts.Text = null;
            inputOtherCosts.Text = null;
            inputClearanceCosts.Text = null;
            inputConstructionCosts.Text = null;
            inputEquipmentCosts.Text = null;
            inputConsultancyCosts.Text = null;
            chkApplySign.Checked = false;
            dataGridCapitalInvestment.Rows.Clear();

            txtCode.Text = "";
            dateSignFinal.Text = "";
            txtDocSignFinal.Text = "";
            txtSignFinalPrice.Text = null;
            txtNote.Text = "";
            chkFinish.Checked = false;
        }
        #endregion

    }
}
